<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.sportStateId" placeholder="请选择赛事类型" filterable>
        <el-option :label="item.valueName" :value="item.valueId" v-for="(item,index) in dictData"
          :key="index"></el-option>
      </el-select>

      <el-input v-model="listQuery.city" placeholder="比赛省市" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <!-- 查询条件隐藏与显示 -->
      <span v-show="showQuery">
        <el-select v-model="listQuery.sportDateChar" placeholder="赛事日期区间" filterable>
          <el-option label="一周内" value="a"></el-option>
          <el-option label="一月内" value="b"></el-option>
          <el-option label="三月内" value="c"></el-option>
        </el-select>
        <el-input v-model="listQuery.minAge" placeholder="最小年龄" style="width: 100px;" class="filter-item"
          @keyup.enter.native="handleFilter" />---
        <el-input v-model="listQuery.maxAge" placeholder="最大年龄" style="width: 100px;" class="filter-item"
          @keyup.enter.native="handleFilter" />
      </span>


      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
        @click="handleCreate">
        新增
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
        @click="handleDownload">
        导出
      </el-button>
      <el-checkbox class="filter-item" style="margin-left:15px;" @change="showMoreQuery">
        更多查询条件
      </el-checkbox>
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;"
      @sort-change="sortChange">
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="60"
        :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>


      <el-table-column label="标题" min-width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="赛事日期" width="100px" align="center" prop='sportDate' :formatter='dateFormatter'>

      </el-table-column>
      <el-table-column label="宣传图片" width="80px" align="center">
        <template slot-scope="{row}">
          <span><img :src='row.sportImg' style='width:50px;height:50px;' /></span>
        </template>
      </el-table-column>

      <el-table-column label="当前状态" width="80px" prop='sportStateId' align="center" :formatter='StateFormatter'>
        <!-- <template slot-scope="{row}">
					<span>{{ row.sportStateId }}</span>
				</template> -->
      </el-table-column>
      <el-table-column label="举办地点" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sportCity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参赛年龄" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.entryAge }}</span>
        </template>
      </el-table-column>

      <el-table-column label="赛事状况" class-name="status-col" prop='sportStatus' :formatter='statusFormatter' width="80">
        <!-- <template slot-scope="{row}">
					<el-tag :type="row.status | statusFilter">
						{{ row.status }}
					</el-tag>
				</template> -->
      </el-table-column>

      <el-table-column label="备注" width="80px" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.des }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.sportStatus!='Y'" size="mini" type="success" @click="handleModifyStatus(row,'Y')">
            启用
          </el-button>
          <el-button v-if="row.sportStatus!='N'" size="mini" @click="handleModifyStatus(row,'N')">
            禁用
          </el-button>
          <el-button v-if="row.sportStatus!='X' && row.sportStatus!='N'" type="warning" size="mini"
            @click="handleModifyStatus(row,'X')">
            延期
          </el-button>
          <el-button v-if="row.sportStatus!='Y' && row.sportStatus!='X'" size="mini" type="danger"
            @click="handleDelete(row,$index)">
            删除
          </el-button>
          <el-button size="mini" type="success" plain @click="handleAddDetail(row,$index)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <!-- 抽屉模态框 赛事编辑-->
    <el-drawer :title="dr_title" :visible.sync="dialog" :before-close="handleClose" direction="rtl"
      custom-class="demo-drawer" size="40%">
      <div class="demo-drawer__content">
        <el-form :inline="true" :model="form" ref="form" :rules="rules" class="demo-form-inline">
          <el-form-item v-if='show_id_item' label="编号ID" :label-width="formLabelWidth">
            <el-input v-model="form.id" :readonly='true'></el-input>
          </el-form-item>
          <el-form-item label="赛事标题" :label-width="formLabelWidth" prop="title">
            <el-input v-model="form.title" size="small"></el-input>
          </el-form-item>
          <el-form-item label="赛事日期" :label-width="formLabelWidth" prop="sportDate">
            <el-input v-model="form.sportDate" type='date' size="small" @change='validDate'></el-input>
          </el-form-item>
          <el-form-item label="赛事类型" :label-width="formLabelWidth" prop="sportStateId">
            <el-select v-model="form.sportStateId" placeholder="请选择角色类型" size="small" filterable>
              <el-option :label="item.valueName" :value="item.valueId" v-for="(item,index) in dictData"
                :key="index"></el-option>
              <!-- <el-option label="管理员" value="1"></el-option>
							<el-option label="开发者" value="2"></el-option>
							<el-option label="员工" value="3"></el-option> -->
            </el-select>
          </el-form-item>
          <el-form-item label="举办地点" :label-width="formLabelWidth" prop="sportCity">
            <el-input v-model="form.sportCity" size="small"></el-input>
          </el-form-item>
          <el-form-item label="参赛年龄" :label-width="formLabelWidth" prop="entryAge">
            <el-input v-model="form.entryAge" type='number' size="small" @blur='validAge'></el-input>
          </el-form-item>

          <el-form-item label="赛事状况" :label-width="formLabelWidth" prop="sportStatus">
            <el-select v-model="form.sportStatus" placeholder="请选择状态" size="small">
              <el-option label="启用" value="Y"></el-option>
              <el-option label="禁用" value="N"></el-option>
              <el-option label="延期" value="N"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="参赛备注" :label-width="formLabelWidth">
            <el-input v-model="form.des" type="textarea" size="small"></el-input>
          </el-form-item>
          <el-form-item label="宣传图片" :label-width="formLabelWidth">
            <el-input v-model="form.sportImg"></el-input>
            <input type="file" size="small" name="files" @change="handleUpload" ref="inputer" accept="application/vnd.ms-powerpoint,
													application/vnd.openxmlformats-officedocument.presentationml.presentation,
													application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document,
													application/pdf">
            <img v-if="picUrl" :src="picUrl" class="avatar" />

            <!-- <el-upload class="avatar-uploader" action="" :show-file-list="false" :on-change="picturePreview"
							:auto-upload="false">
							<img v-if="imageUrl" :src="imageUrl" class="avatar" />
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
						<el-button type="warning" class="cancelBtn" v-show="imageUrl"
							@click="cancelUpload">取消图片</el-button>
						<el-button style="margin-left: 10px;" size="small" type="success"
							@click="submitUpload">上传到服务器</el-button> -->
          </el-form-item>


        </el-form>
        <div class="demo-drawer__footer">
          <el-button icon="el-icon-error" @click="cancelForm">取 消</el-button>
          <el-button icon="el-icon-refresh-right" type="warning" @click="resetForm('form')">重置</el-button>
          <el-button icon="el-icon-check" type="success" @click="handleClose('form')"
            :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 抽屉模态框 赛事详情编辑-->
    <el-drawer :title="dr_detail_title" :visible.sync="detail_dialog" :before-close="handleClose" direction="rtl"
      custom-class="demo-drawer" size="40%">
      <div class="demo-drawer__content">
        <el-form :inline="true" :model="form_detail" ref="form_detail" :rules="detail_rules" class="demo-form-inline">
          <el-form-item v-if='show_detail_id_item' label="ID" :label-width="formLabelWidth">
            <el-input v-model="form_detail.id" :readonly='true' size="small"></el-input>
          </el-form-item>
          <el-form-item label="赛事ID" :label-width="formLabelWidth">
            <el-input v-model="form_detail.sportId" :readonly='true' size="small"></el-input>
          </el-form-item>
          <el-form-item label="赛事标题" :label-width="formLabelWidth">
            <el-input v-model="form_detail.title" :readonly='true' size="small"></el-input>
          </el-form-item>
          <el-form-item label="宣传图片" :label-width="formLabelWidth">
            <el-input v-model="form_detail.sportImg" :readonly='true' size="small"></el-input>
          </el-form-item>
          <el-form-item label="赛事日期" :label-width="formLabelWidth">
            <el-input v-model="form_detail.sportDate" :readonly='true' type='date' size="small"></el-input>
          </el-form-item>
          <el-form-item label="赛事类型" :label-width="formLabelWidth">
            <el-input v-model="form_detail.sportStateId" :readonly='true' size="small"></el-input>
          </el-form-item>
          <el-form-item label="报名费用" :label-width="formLabelWidth" prop="price">
            <el-input v-model="form_detail.price" size="small"></el-input>
          </el-form-item>
          <el-form-item label="主办方" :label-width="formLabelWidth" prop="sponsor">
            <el-input v-model="form_detail.sponsor" type='text' size="small"></el-input>
          </el-form-item>

          <el-form-item label="报名日期时间" :label-width="formLabelWidth" prop="entryDate">
            <el-input v-model="form_detail.entryDate" type='text' size="small"></el-input>
          </el-form-item>
          <el-form-item label="具体地点" :label-width="formLabelWidth" prop="sportAddress">
            <el-input v-model="form_detail.sportAddress" type='textarea' size="small"></el-input>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button icon="el-icon-error" size="mini" @click="cancelForm_detail">取 消</el-button>
          <el-button icon="el-icon-refresh-right" size="mini" type="warning" @click="resetForm('form')">重置</el-button>
          <el-button icon="el-icon-check" size="mini" type="success" @click="handleDetailClose('form')"
            :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>


    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    fetchList,
    del,
    updateStatus,
    add,
    update,
    uploadImg,
    fetchPv,
    createArticle,
    updateArticle
  } from '@/api/sportApi';

  import {
    fetchDictList
  } from '@/api/dictApi'

  import {
    fetchBySportId,
    doEdit
  } from '@/api/sportDetailApi'

  import waves from '@/directive/waves' // waves directive
  import {
    parseTime
  } from '@/utils'

  import {
    getToken
  } from '@/utils/auth'

  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  const calendarTypeOptions = [{
      key: 'CN',
      display_name: 'China'
    },
    {
      key: 'US',
      display_name: 'USA'
    },
    {
      key: 'JP',
      display_name: 'Japan'
    },
    {
      key: 'EU',
      display_name: 'Eurozone'
    }
  ]

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'ComplexTable',
    components: {
      Pagination
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          Y: 'success',
          N: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          pageNo: 1,
          pageSize: 20,
          sportStateId: '',
          sportDateChar: '',
          city: '',
          minAge: '',
          maxAge: '',
          sort: '+id'
        },
        importanceOptions: [1, 2, 3],
        calendarTypeOptions,
        sortOptions: [{
          label: 'ID Ascending',
          key: '+id'
        }, {
          label: 'ID Descending',
          key: '-id'
        }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          type: '',
          status: 'published'
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          title: [{
            required: true,
            message: '必填字段',
            trigger: 'blur'
          }],
          sportDate: [{
            required: true,
            message: '必填字段',
            trigger: 'blur'
          }],
          sportStateId: [{
            required: true,
            message: '必填字段',
            trigger: 'blur'
          }],
          entryAge: [{
            required: true,
            message: '必填字段',
            trigger: 'blur'
          }],
          sportCity: [{
            required: true,
            message: '必填字段',
            trigger: 'blur'
          }],
          sportStatus: [{
            required: true,
            message: '必填字段',
            trigger: 'change'
          }]
        },
        detail_rules: {
          price: [{
            required: true,
            message: '必填字段',
            trigger: 'blur'
          }],
          sponsor: [{
            required: true,
            message: '必填字段',
            trigger: 'blur'
          }],
          entryDate: [{
            required: true,
            message: '必填字段',
            trigger: 'blur'
          }],
          sportAddress: [{
            required: true,
            message: '必填字段',
            trigger: 'blur'
          }]
        },
        downloadLoading: false,
        dialog: false,
        detail_dialog: false,
        loading: false,
        form: {
          id: '',
          title: '',
          sportDate: '',
          sportImg: '',
          sportStateId: '',
          sportCity: '',
          sportStatus: '',
          entryAge: '',
          des: ''
        },

        form_detail: {
          id: '',
          sportId: '',
          title: '',
          sportImg: '',
          sportDate: '',
          sportStateId: '',
          price: '',
          sponsor: '',
          entryDate: '',
          sportAddress: ''
        },

        formLabelWidth: '80px',
        dr_title: '',
        dr_detail_title: '',
        show_id_item: false,
        show_detail_id_item: false,
        dictData: [],
        file: "",
        imageUrl: "",
        picUrl: '',
        showQuery: false
      }
    },
    created() {
      this.getList();
      this.getDictList();
    },
    methods: {
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          console.info('response==>', response)
          this.list = response.data.records;
          this.total = response.data.total;

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      /* 格式状态 */
      statusFormatter(row, column, cellValue, index) {
        return cellValue == 'Y' ? '已启用' : cellValue == 'N' ? '已禁用' : '已延期';
      },
      /* 赛事state格式化 */
      StateFormatter(row, column, cellValue, index) {
        var str = '';
        switch (cellValue) {
          case 0:
            str = '未开始';
            break;
          case 1:
            str = '报名中';
            break;
          case 2:
            str = '比赛中';
            break;
          case 3:
            str = '已结束';
            break;
          case 4:
            str = '已延期';
            break;
          case 4:
            str = '已延期';
            break;
          default:
            str = '未知';
            break;
        }
        return str;
      },

      dateFormatter(row, column, cellValue, index) {
        return cellValue.substring(0, 10);
      },

      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, _status) {
        console.info('row=>', row)
        console.info('status=>', _status);
        this.$confirm('此操作将更改编号为' + row.id + '的数据状态, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateStatus({
            id: row.id,
            status: _status
          }).then(res => {
            if (res.code == '201') {
              this.$message({
                type: 'success',
                message: res.msg
              });
              this.getList();
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              });
            }

          }).catch(err => {
            this.$message({
              type: 'error',
              message: '操作异常，请联系管理员！'
            });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // detail详情操作
      handleAddDetail(row) {
        // 当模态框打开的时候调用赛事详情存在是否的方法
        // 需要注意：
        // 1、如果字面量赋值是拆分为前后2部分进行赋值，则可能会出现后边覆盖前边赋值的bug，比如前边的值被清空
        // 2、还会导致表单中的属性受到影响，比如：只读，如果前边定义有只读，则后边都会受到影响
        console.info('row==>', row)
        if (row.id != '') {
          this.form_detail.sportId = row.id;
          this.form_detail.title = row.title;
          this.form_detail.sportImg = row.sportImg;
          this.form_detail.sportDate = row.sportDate;
          this.form_detail.sportStateId = row.sportStateId;
          // this.form_detail = {
          // 	sportId: row.id,
          // 	title: row.title,
          // 	sportImg: row.sportImg,
          // 	sportDate: row.sportDate,
          // 	sportStateId: row.sportStateId
          // }
          this.querySportDetailIsHas(row.id)
          console.info('this.form_detail==>', this.form_detail)
        }
        this.detail_dialog = true;
      },
      // 判断赛事详情信息是否已存在
      querySportDetailIsHas(_sportId) {
        fetchBySportId({
          sportId: _sportId
        }).then(res => {
          console.info('querySportDetailIsHas=>', res);
          if (res.code == 200) {
            this.show_detail_id_item = true;
            // 有详情信息，则将详情信息回显到对应的输入框中
            // 赛事详情的id、报名费、主办方、报名日期时间、具体地点，这些信息需要从赛事详情中获取并回显
            // 赛事详情的其余部分：赛事的编号、赛事的标题、赛事的宣传图、赛事的日期、赛事的当前状态
            // 其余部分建议从当前赛事中获取并回显，避免重复获取
            this.dr_detail_title = '赛事详情修改';
            this.form_detail.id = res.data.id;
            this.form_detail.price = res.data.price;
            this.form_detail.sponsor = res.data.sponsor;
            this.form_detail.entryDate = res.data.entryDate;
            this.form_detail.sportAddress = res.data.sportAddress;
          } else {
            this.show_detail_id_item = false;
            // 如果没有查询到值则将模态框中对应的部分清空
            this.dr_detail_title = '赛事详情添加';
            this.form_detail.id = '';
            this.form_detail.price = '';
            this.form_detail.sponsor = '';
            this.form_detail.entryDate = '';
            this.form_detail.sportAddress = '';
          }
        }).catch(err => {
          console.error(err);
        })
      },

      cancelForm_detail() {
        this.loading = false;
        this.detail_dialog = false;
        this.$refs['form_detail'].resetFields();
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },

      sortChange(data) {
        const {
          prop,
          order
        } = data;
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      showMoreQuery() {
        this.showQuery = !this.showQuery;
      },

      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },
      handleCreate() {
        this.dr_title = '新增数据';
        this.dialog = true;
        this.show_id_item = false;
        this.clearForm();
        this.getDictList();
      },
      clearForm() {
        this.form = {
          id: '',
          title: '',
          sportDate: '',
          sportImg: '',
          sportStateId: '',
          sportCity: '',
          entryAge: '',
          des: '',
          sportStatus: 'Y'
        }
        this.picUrl = '';
      },

      handleUpdate(row) {
        this.dr_title = '编辑数据';
        this.dialog = true;
        this.show_id_item = true;
        console.info('row=>', row);
        this.clearForm();
        this.form = {
          id: row.id,
          title: row.title,
          sportDate: row.sportDate,
          sportImg: row.sportImg,
          sportStateId: row.sportStateId,
          sportCity: row.sportCity,
          entryAge: row.entryAge,
          des: row.des,
          sportStatus: row.sportStatus,
        };
        this.getDictList();
      },

      handleDelete(row, index) {
        this.$confirm('此操作将永久删除编号为' + row.id + '的数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(row.id).then(res => {
            if (res.code == '201') {
              this.$message({
                message: res.msg,
                type: 'success'
              });
            } else {
              this.$message.error(res.msg);
            }
          }).catch(err => {
            console.error(err);
            this.$message.error('操作异常，请联系管理员！');
          })
          //this.list.splice(index, 1)
          this.getList();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['编号', '标题', '赛事日期', '宣传图片', '当前状态', '举办地点', '参赛年龄', '赛事状况', '备注']
          const filterVal = ['id', 'title', 'sportDate', 'sportImg', 'sportStateId', 'sportCity',
            'entryAge', 'sportStatus', 'des'
          ]
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'sport-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },

      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      },
      // 字典表中获取对应角色下拉数据
      getDictList() {
        fetchDictList('sport_code').then(res => {
          if (res.code == '200') {
            this.dictData = res.data;
          }
        }).catch(err => {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        })
      },

      handleClose(formName) {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.$confirm('确定要提交表单吗？')
              .then(() => {
                this.loading = true;
                if (this.form.id == '') {
                  this.insert();
                } else {
                  this.edit();
                }
                this.loading = false;
                this.dialog = false;
              })
              .catch((err) => {
                console.log('error submit!!');
              });

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 赛事详情编辑当关闭时进行的处理
      handleDetailClose(formName) {
        this.$refs['form_detail'].validate((valid) => {
          if (valid) {
            this.$confirm('确定要提交详情表单吗？')
              .then(() => {
                this.loading = true;
                this.doDetailEdit();
                this.loading = false;
                this.detail_dialog = false;
              })
              .catch((err) => {
                console.log('catch error submit!!');
              });

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 添加或修改赛事详情
      doDetailEdit() {
        doEdit(this.form_detail).then(res => {
          if (res.code == '201') {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            // 添加或修改成功后，跳转至赛事详情列表中
            this.$router.push({
              path: '/sport/sportDetail'
            })
          } else {
            this.$message.error(res.msg);
          }
        }).catch(err => {
          console.error(err);
          this.$message.error('操作异常，请联系管理员！');
        })
      },

      cancelForm() {
        this.loading = false;
        this.dialog = false;
        this.$refs['form'].resetFields();
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },

      formatDate(date) {
        let yyyy = date.getFullYear();
        let mm = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
        let dd = String(date.getDate()).padStart(2, '0');
        let hh = String(date.getHours()).padStart(2, '0');
        let min = String(date.getMinutes()).padStart(2, '0');
        let ss = String(date.getSeconds()).padStart(2, '0');
        return `${yyyy}-${mm}-${dd} ${hh}:${min}:${ss}`;
      },
      /* 比赛日期验证有效性、合理性 */
      validDate(value) {
        console.info('value==>', value)
        let _localDate = this.formatDate(new Date());
        if (value < _localDate) {
          this.$message.error('输入日期错误：日期必须大于当前日期！');
          this.form.sportDate = ''
        }
      },

      validAge(event) {
        console.info('event==>', event.target.value)
        let _age = event.target.value;
        if (_age < 1 || _age > 70) {
          this.$message.error('输入年龄错误：年龄必须介于1到70之间！');
          this.form.entryAge = '';
        }
      },

      insert() {
        add(this.form).then(res => {
          if (res.code == '201') {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.getList();
          } else {
            this.$message.error(res.msg);
          }
        }).catch(err => {
          console.error(err);
          this.$message.error('操作异常，请联系管理员！');
        })
      },
      edit() {
        update(this.form).then(res => {
          if (res.code == '201') {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.getList();
          } else {
            this.$message.error(res.msg);
          }
        }).catch(err => {
          console.error(err);
          this.$message.error('操作异常，请联系管理员！');
        })
      },

      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      //onchange:预览图片
      picturePreview(file, fileList) {
        // console.log("fffff", file.raw);
        //预览图片
        if (window.createObjectURL != undefined) {
          this.imageUrl = window.createObjectURL(file.raw);
        } else if (window.URL != undefined) {
          this.imageUrl = window.URL.createObjectURL(file.raw);
        } else if (window.webkitURL != undefined) {
          this.imageUrl = window.webkitURL.createObjectURL(file.raw);
        }
        this.file = file.raw;
      },
      //取消上传
      cancelUpload() {
        this.imageUrl = "";
        this.file = "";
      },
      //文件上传 async这里本来想设置同步，但是怎么也改不了同步，还是异步
      async uploadPic() {
        const formData = new FormData();
        formData.append("file", this.file);
        formData.append("fileType", "IMAGE");
        let picName = new Date().getTime() + "";
        formData.append("picName", picName);

        this.form.picPath = picName;

        uploadImg(formData).then(res => {
          console.log('uploadres==>', res)
        }).catch(err => {
          this.$message.error("上传失败");
        })
        this.imageUrl = "";
      },
      submitUpload() {
        console.log("图片上传");
        this.uploadPic();
      },

      /* 文件上传 */
      handleUpload(e) {
        /* hack判断当前文件是否为空 */
        let files = e.target.files || e.dataTransfer.files;
        if (!files.length) return;

        /* 创建一个form对象 */
        let formData = new FormData();
        formData.append('files', files[0]); // 添加到form对象中
        console.info('res=>', formData);
        console.info('files[0=>', files[0]);

        uploadImg(formData)
          .then(res => {
            console.info('res=>', res);
            this.form.sportImg = res.data;
            this.picUrl = res.data;
          })
          .catch(err => {
            console.info('err=>', err);
          })
      },
    }
  }
</script>

<style scoped>
  .demo-drawer__footer {
    display: flex;
    margin: 0 30px;
  }

  .demo-drawer__footer button {
    flex: 1;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 58px;
    height: 58px;
    border: 1px solid;
    line-height: 58px;
    text-align: center;
  }

  .avatar {
    width: 78px;
    height: 78px;
    display: block;
  }

  .filter-container div {
    margin: 1vw 1vw;
  }
</style>
